package com.demo.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.demo.springcloud.entity.R;
import com.demo.springcloud.feign.paymentService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author hxg
 * @version 1.0
 * @date 2022/1/10 22:06
 */
@RestController
public class alibabaOrderController {
    @Resource
    private RestTemplate restTemplate;

    @Value("${service-url.nacos-user-service}")
    private String serviceURL;

    @GetMapping("/consumer/payment/nacos/{id}")
    @SentinelResource(value = "paymentBlock",blockHandler = "fallBlock",fallback = "fallMethod")
    public String getPaymentInfo(@PathVariable("id")Long id){
        //ribon调用实现
        String s = restTemplate.getForObject(serviceURL + "/payment/" + id, String.class);
        if (id == 4) {
            throw new IllegalArgumentException("非法参数异常");
        }else if(s == null){
            throw new NullPointerException("空指针异常");
        }
        return s;
    }

    public String fallBlock(Long id, BlockException e){
        return "sentinel error"+id+e.getMessage();
    }

    public String fallMethod(Long id,Throwable e){
        return "server error sentinel"+id+e.getMessage();
    }

    //feign调用实现
    @Resource
    private paymentService paymentService;

    @GetMapping("/consumer/payment/{id}")
    public R paymentTest(@PathVariable("id")Long id){
        return paymentService.paymentTest(id);
    }

}
